package com.song.osclient.qrcode;


import android.graphics.Rect;
import android.hardware.Camera;
import android.os.Handler;

import com.google.zxing.BinaryBitmap;
import com.google.zxing.PlanarYUVLuminanceSource;
import com.google.zxing.ReaderException;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;

/**
 * Created by Administrator on 2015/12/16.
 */
public class PreviewDecodeHandler extends DecodeHandler implements Camera.PreviewCallback {
    private Rect rect;
    private boolean running;
    private Handler handler;

    public PreviewDecodeHandler(Rect rect, Handler handler) {
        this.rect = rect;
        this.handler = handler;
    }

    @Override
    public void onPreviewFrame(byte[] data, Camera camera) {
        if (running) {
            return;
        }
        decode(data, camera);
    }

    private void decode(byte[] data, Camera camera) {
        Camera.Size size = camera.getParameters().getPreviewSize();
        running = true;
        // 这里需要将获取的data翻转一下，因为相机默认拿的的横屏的数据
        byte[] rotatedData = new byte[data.length];
        for (int y = 0; y < size.height; y++) {
            for (int x = 0; x < size.width; x++)
                rotatedData[x * size.height + size.height - y - 1] = data[x + y * size.width];
        }

        // 宽高也要调整
        int tmp = size.width;
        size.width = size.height;
        size.height = tmp;

        Result rawResult = null;
        // Go ahead and assume it's YUV rather than die.
        PlanarYUVLuminanceSource source = new PlanarYUVLuminanceSource(rotatedData, size.width, size.height, rect.left, rect.top, rect.width(), rect.height(), false);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        try {
            rawResult = multiFormatReader.decodeWithState(bitmap);
        } catch (ReaderException re) {
            // continue
        } finally {
            multiFormatReader.reset();
        }
        if (rawResult != null) {
            // Don't log the barcode contents for security.
            if (handler != null) {
                handler.sendMessage(handler.obtainMessage(Constant.VALUE_DECODE_SUCCESS, rawResult.getText()));
            }
        }
        running = false;
    }
}
